import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'default_error.dart';
import 'form_modal.dart';
import 'radio_field.dart';
import 'input_field.dart';
import 'switch_field.dart';
import 'picker_field.dart';

import 'package:test_app/core/design_system/extensions/extensions.dart';
import 'package:test_app/core/utils/toast/toast_util.dart';

class BaseForm extends StatefulWidget {
  const BaseForm({super.key});

  @override
  State<BaseForm> createState() => _BaseFormState();
}

class _BaseFormState extends State<BaseForm> {
  final _formKey = GlobalKey<FormBuilderState>();

  /// 每个字段一个 key，方便手动控制和重置
  final Map<String, GlobalKey<FormBuilderFieldState>> _fieldKeys = {};

  /// 表单配置（后续可以从接口/其它地方动态生成）
  late final List<FormModal> _items = <FormModal>[
    FormModal(
      label: '手机号',
      field: 'phone',
      type: FormFieldType.input,
      require: true,
      placeholder: '请输入手机号',
      validator: FormBuilderValidators.compose([
        FormBuilderValidators.required(errorText: '手机号不能为空'),
      ]),
    ),
    FormModal(
      label: '昵称',
      field: 'name',
      type: FormFieldType.input,
      placeholder: '请输入昵称',
    ),
    FormModal(label: '是否使用优惠券', field: 'useCoupon', type: FormFieldType.toggle),
    FormModal(
      label: '状态',
      field: 'status',
      require: true,
      type: FormFieldType.radio,
      options: const <TDRadio>[
        TDRadio(title: '启用', id: 'enabled'),
        TDRadio(title: '禁用', id: 'disabled'),
      ],
    ),
    FormModal(
      label: '所在城市',
      field: 'city',
      require: true,
      type: FormFieldType.picker,
      placeholder: '请选择城市',
      options: {
        '广东省': {
          '深圳市': ['南山区', '宝安区', '罗湖区', '福田区'],
          '广州市': ['天河区', '越秀区', '白云区', '花都区'],
          '佛山市': ['顺德区', '南海区', '禅城区']
        },
        '浙江省': {
          '杭州市': ['西湖区', '余杭区', '萧山区'],
          '宁波市': ['江东区', '北仑区', '奉化市'],
          '温州市': ['鹿城区', '瑞安市', '乐清市']
        },
      },
    ),
  ];

  bool _validate() {
    _formKey.currentState?.save();
    final isValidate = _formKey.currentState?.validate() ?? false;

    if (isValidate) {
      ToastUtil.success('校验通过');
      return true;
    } else {
      ToastUtil.error('请完善表单信息');
      return false;
    }
  }

  Map<String, dynamic>? _getFormValues() {
    _formKey.currentState?.save();
    final formData = _formKey.currentState?.value;
    debugPrint('Form values => $formData');
    return formData;
  }

  void _reset() {
    _formKey.currentState?.reset();
    setState(() {
      for (final key in _fieldKeys.values) {
        key.currentState?.reset();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return FormBuilder(
      key: _formKey,
      child: [
        for (final item in _items) _buildField(context, item),

        TDButton(
          text: '获取表单数据',
          isBlock: true,
          size: TDButtonSize.large,
          type: TDButtonType.fill,
          shape: TDButtonShape.rectangle,
          theme: TDButtonTheme.primary,
          margin: EdgeInsets.zero,
          onTap: _getFormValues,
        ),
        TDButton(
          text: '校验表单',
          isBlock: true,
          size: TDButtonSize.large,
          type: TDButtonType.outline,
          shape: TDButtonShape.rectangle,
          theme: TDButtonTheme.primary,
          margin: EdgeInsets.zero,
          onTap: _validate,
        ),
        TDButton(
          text: '重置表单',
          isBlock: true,
          size: TDButtonSize.large,
          type: TDButtonType.outline,
          shape: TDButtonShape.rectangle,
          theme: TDButtonTheme.primary,
          margin: EdgeInsets.zero,
          onTap: _reset,
        ),
      ].toColumn(spacing: 10).padAll(10),
    );
  }

  /// 根据 FormModal 配置构建不同类型的表单项
  Widget _buildField(BuildContext context, FormModal item) {
    final fieldKey = _fieldKeys.putIfAbsent(
      item.field,
      () => GlobalKey<FormBuilderFieldState>(),
    );

    // 外部完全自定义
    if (item.slot != null) {
      return item.slot!(fieldKey);
    }

    switch (item.type) {
      case FormFieldType.input:
        return buildInputFieldWidget(item: item, fieldKey: fieldKey);
      case FormFieldType.toggle:
        return buildSwitchField(item: item, fieldKey: fieldKey);
      case FormFieldType.radio:
        return buildRadioFieldWidget(item: item, fieldKey: fieldKey);
      case FormFieldType.picker:
        return _wrapFieldShell(
          label: item.label,
          height: 58,
          child: buildPickerField(item: item, fieldKey: fieldKey),
        );
    }
  }

  /// 统一行容器（左边 label，右边内容），保持与 InputView 一致的样式
  ///
  /// [height] 为空时不限制高度，让子内容自行撑开（多选等场景需要多行展示）。
  Widget _wrapFieldShell({
    required String label,
    required Widget child,
    double? height,
  }) {
    final base = [
      Text(label).padRight(20),
      Expanded(child: child),
    ].toRow().padHorizontal(16);

    final widget = height == null ? base : base.height(height);

    return widget.backgroundColor(const Color(0xFFFFFFFF)).clipRadius(8);
  }

}
